<template>
  <div class="chat-view">
    <div class="chat-header">
      <el-button @click="router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <div class="chat-info">
        <h3>{{ consultation.title }}</h3>
        <p>与 {{ consultation.lawyerName }} 律师的对话</p>
      </div>
      <el-tag :type="getStatusType(consultation.status)">
        {{ getStatusText(consultation.status) }}
      </el-tag>
    </div>

    <div class="chat-container">
      <!-- 消息列表 -->
      <div class="messages-area" ref="messagesArea">
        <div v-if="messagesLoading" class="loading-messages">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else class="messages-list">
          <div
            v-for="message in messages"
            :key="message.id"
            :class="[
              'message-item',
              message.senderId === userStore.user?.id ? 'own-message' : 'other-message',
            ]"
          >
            <div class="message-avatar">
              <el-avatar :size="40" :src="getAvatar(message)" />
            </div>
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">{{ getSenderName(message) }}</span>
              </div>
              <div class="message-bubble">
                <div v-if="message.messageType === 'text'" class="text-content">
                  {{ message.content }}
                </div>
                <div v-else-if="message.message_type === 'file'" class="file-content">
                  <el-icon><Document /></el-icon>
                  <a :href="message.fileUrl" target="_blank">{{ getFileName(message.fileUrl) }}</a>
                </div>
                <div class="message-time">
                  {{ formatTime(message.createdAt) }}
                  <span v-if="message.isRead" class="read-indicator">已读</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-toolbar">
          <el-button type="text" @click="toggleFileUpload">
            <el-icon><FolderAdd /></el-icon>
          </el-button>

          <div v-if="showFileUpload" class="file-upload-section">
            <el-upload action="#" :before-upload="handleFileUpload" :show-file-list="false">
              <el-button type="primary" size="small">选择文件</el-button>
            </el-upload>
          </div>
        </div>

        <div class="input-container">
          <el-input
            v-model="newMessage"
            type="textarea"
            :rows="3"
            placeholder="输入您的消息..."
            @keypress.enter.prevent="sendMessage"
          />
          <el-button
            type="primary"
            class="send-btn"
            :disabled="!newMessage.trim()"
            @click="sendMessage"
          >
            <el-icon><Promotion /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, inject, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userInfoStore } from '@/stores/userinfo'
import { ArrowLeft, Document, FolderAdd, Promotion } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const api = inject('$api')
const userStore = userInfoStore()

const consultationId = ref(route.params.id)
const consultation = ref({})
const messages = ref([])
const messagesLoading = ref(false)
const newMessage = ref('')
const showFileUpload = ref(false)
const messagesArea = ref(null)
const userInfoMap = ref({})

// 新增：记录当前最新消息的ID和时间戳
const lastMessageId = ref(null)
const lastUpdateTime = ref(null)

let pollInterval = null

// 新增：判断是否为当前用户的消息
const isCurrentUserMessage = (message) => {
  return message.senderId === userStore.user?.id
}

const fetchConsultationDetail = async () => {
  try {
    const response = await api.consultation.getConsultationDetail(consultationId.value)
    if (response.code === 200) {
      consultation.value = response.data
    }
  } catch (error) {
    console.error('获取咨询详情失败:', error)
  }
}

const fetchMessages = async () => {
  try {
    const response = await api.consultation.getMessages(consultationId.value)
    if (response.code === 200) {
      // 检查是否有新消息
      const hasNewMessages = checkForNewMessages(response.data)

      if (hasNewMessages) {
        messages.value = response.data
        await fetchUserInfo()
        await nextTick()
        scrollToBottom()

        // 更新最新消息记录
        if (response.data.length > 0) {
          lastMessageId.value = response.data[response.data.length - 1].id
          lastUpdateTime.value = new Date().getTime()
        }
      }
    }
  } catch (error) {
    console.error('获取消息失败:', error)
  }
}

// 新增：检查是否有新消息
const checkForNewMessages = (newMessages) => {
  // 如果之前没有消息，直接返回true
  if (messages.value.length === 0 && newMessages.length > 0) {
    return true
  }

  // 如果消息数量不同，说明有新消息
  if (newMessages.length !== messages.value.length) {
    return true
  }

  // 检查最后一条消息是否不同
  if (newMessages.length > 0 && messages.value.length > 0) {
    const currentLastMessage = messages.value[messages.value.length - 1]
    const newLastMessage = newMessages[newMessages.length - 1]

    if (currentLastMessage.id !== newLastMessage.id) {
      return true
    }

    // 检查消息内容是否有更新（比如已读状态变化）
    if (
      currentLastMessage.isRead !== newLastMessage.isRead ||
      currentLastMessage.content !== newLastMessage.content
    ) {
      return true
    }
  }

  return false
}

// 新增：获取用户公开信息（与ConsultationDetailView一致）
const fetchUserInfo = async () => {
  try {
    // 提取所有消息中的发送者ID
    const senderIds = [...new Set(messages.value.map((msg) => msg.senderId))]

    if (senderIds.length > 0) {
      const response = await api.user.getUsersPublicInfoBatch(senderIds)
      if (response.code === 200) {
        // 将用户信息转换为映射表
        response.data.forEach((user) => {
          userInfoMap.value[user.id] = user
        })
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const sendMessage = async () => {
  if (!newMessage.value.trim()) return

  try {
    const messageData = {
      content: newMessage.value.trim(),
      messageType: 'text',
      senderId: userStore.user?.id,
    }

    console.log('准备发送消息:', {
      consultationId: consultationId.value,
      messageData: messageData,
    })

    const response = await api.consultation.sendMessage(consultationId.value, messageData)
    if (response.code === 200) {
      newMessage.value = ''
      // 发送消息后强制刷新消息列表
      await forceRefreshMessages()
      await markMessagesAsRead()
    }
  } catch (error) {
    ElMessage.error('发送消息失败')
  }
}

// 新增：强制刷新消息列表（用于发送消息后）
const forceRefreshMessages = async () => {
  try {
    messagesLoading.value = true
    const response = await api.consultation.getMessages(consultationId.value)
    if (response.code === 200) {
      messages.value = response.data
      await fetchUserInfo()
      await nextTick()
      scrollToBottom()

      // 更新最新消息记录
      if (response.data.length > 0) {
        lastMessageId.value = response.data[response.data.length - 1].id
        lastUpdateTime.value = new Date().getTime()
      }
    }
  } catch (error) {
    console.error('获取消息失败:', error)
  } finally {
    messagesLoading.value = false
  }
}

// 新增：标记消息为已读
const markMessagesAsRead = async () => {
  try {
    const unreadMessages = messages.value.filter(
      (msg) => !msg.isRead && msg.senderId !== userStore.user?.id,
    )

    if (unreadMessages.length > 0) {
      const messageIds = unreadMessages.map((msg) => msg.id)
      await api.consultation.markAsRead(consultationId.value, messageIds)

      // 更新本地消息状态
      messages.value.forEach((msg) => {
        if (messageIds.includes(msg.id)) {
          msg.isRead = true
        }
      })
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

const handleFileUpload = async (file) => {
  try {
    // 这里需要实现文件上传逻辑
    const formData = new FormData()
    formData.append('file', file)

    // 模拟文件上传
    const fileUrl = URL.createObjectURL(file)

    const messageData = {
      messageType: 'file',
      fileUrl: fileUrl,
      content: file.name,
      senderId: userStore.user?.id,
    }

    const response = await api.consultation.sendMessage(consultationId.value, messageData)
    if (response.code === 200) {
      showFileUpload.value = false
      await fetchMessages()
      ElMessage.success('文件发送成功')
    }
  } catch (error) {
    ElMessage.error('文件发送失败')
  }
  return false // 阻止默认上传
}

const toggleFileUpload = () => {
  showFileUpload.value = !showFileUpload.value
}

const scrollToBottom = () => {
  if (messagesArea.value) {
    messagesArea.value.scrollTop = messagesArea.value.scrollHeight
  }
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    active: 'primary',
    completed: 'success',
    cancelled: 'info',
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待接单',
    active: '进行中',
    completed: '已完成',
    cancelled: '已取消',
  }
  return texts[status] || status
}

// 使用用户信息映射获取头像
const getAvatar = (message) => {
  const userInfo = userInfoMap.value[message.senderId]
  if (userInfo && userInfo.avatarUrl) {
    return userInfo.avatarUrl
  }

  // 默认头像（与ConsultationDetailView一致）
  return message.senderType === 'lawyer' ? '/default-lawyer-avatar.png' : '/default-user-avatar.png'
}

// 获取发送者姓名（与ConsultationDetailView一致）
const getSenderName = (message) => {
  const userInfo = userInfoMap.value[message.senderId]

  // 如果有用户信息，使用真实姓名
  if (userInfo && userInfo.realName) {
    return userInfo.realName
  }

  // 判断是否为当前用户
  if (isCurrentUserMessage(message)) {
    return '我'
  }

  // 默认显示
  return message.senderType === 'lawyer' ? '律师' : '用户'
}

const getFileName = (url) => {
  return url.split('/').pop() || '文件'
}

// 使用更完整的时间格式化
const formatTime = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now - date
  const diffMins = Math.floor(diffMs / 60000)

  if (diffMins < 1) {
    return '刚刚'
  } else if (diffMins < 60) {
    return `${diffMins}分钟前`
  } else if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return (
      date.toLocaleDateString('zh-CN') +
      ' ' +
      date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    )
  }
}

// 优化轮询逻辑：只在有新消息时刷新
const startPolling = () => {
  pollInterval = setInterval(async () => {
    // 记录当前滚动位置
    const oldScrollHeight = messagesArea.value ? messagesArea.value.scrollHeight : 0
    const oldScrollTop = messagesArea.value ? messagesArea.value.scrollTop : 0

    await fetchMessages()

    // 如果有新消息且用户已经在底部附近，自动滚动
    if (messagesArea.value) {
      const isNearBottom = oldScrollHeight - oldScrollTop - messagesArea.value.clientHeight < 100
      if (isNearBottom) {
        await nextTick()
        scrollToBottom()
      }
    }
  }, 5000) // 每5秒检查一次
}

const stopPolling = () => {
  if (pollInterval) {
    clearInterval(pollInterval)
    pollInterval = null
  }
}

onMounted(() => {
  fetchConsultationDetail()
  forceRefreshMessages()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
/* 优化后的样式 - 适配HomeView布局 */
.chat-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden; /* 关键：防止外层滚动 */
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #e0e0e0;
  background: #f9fafb;
  flex-shrink: 0;
  min-height: 70px;
  box-sizing: border-box;
}

.back-btn {
  margin-right: 15px;
}

.chat-info {
  flex: 1;
  min-width: 0; /* 允许文本收缩 */
}

.chat-info h3 {
  margin: 0 0 4px 0;
  color: #1a3a5f;
  font-size: 1rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-info p {
  margin: 0;
  color: #666;
  font-size: 0.85rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.messages-area {
  flex: 1;
  overflow-y: auto;
  padding: 15px 20px;
  background: #f5f5f5;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.own-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content-wrapper {
  max-width: 65%;
  display: flex;
  flex-direction: column;
}

.own-message .message-content-wrapper {
  align-items: flex-end;
}

.other-message .message-content-wrapper {
  align-items: flex-start;
}

.message-header {
  margin-bottom: 4px;
  padding: 0 6px;
}

.sender-name {
  font-size: 0.7rem;
  color: #666;
  font-weight: 500;
}

.own-message .message-header {
  display: none;
}

.message-bubble {
  max-width: 100%;
  padding: 10px 14px;
  border-radius: 16px;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  line-height: 1.4;
}

.own-message .message-bubble {
  background: #1a3a5f;
  color: white;
  border-bottom-right-radius: 6px;
}

.other-message .message-bubble {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 6px;
}

.file-content {
  display: flex;
  align-items: center;
  gap: 6px;
}

.file-content a {
  color: inherit;
  text-decoration: none;
  font-size: 0.9rem;
}

.file-content a:hover {
  text-decoration: underline;
}

.message-time {
  font-size: 0.65rem;
  opacity: 0.7;
  margin-top: 4px;
  text-align: right;
}

.read-indicator {
  margin-left: 4px;
  font-style: italic;
  font-size: 0.6rem;
}

.other-message .message-time {
  text-align: left;
}

.input-area {
  border-top: 1px solid #e0e0e0;
  padding: 12px 20px;
  background: white;
  flex-shrink: 0;
  box-sizing: border-box;
}

.input-toolbar {
  margin-bottom: 8px;
}

.file-upload-section {
  margin-top: 8px;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 4px;
  font-size: 0.9rem;
}

.input-container {
  display: flex;
  gap: 8px;
  align-items: flex-end;
}

.input-container .el-textarea {
  flex: 1;
}

.input-container .el-textarea :deep(.el-textarea__inner) {
  font-size: 0.9rem;
  line-height: 1.4;
}

.send-btn {
  height: 68px;
  flex-shrink: 0;
  font-size: 0.9rem;
}

.loading-messages {
  padding: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chat-header {
    padding: 10px 15px;
    min-height: 60px;
  }

  .message-content-wrapper {
    max-width: 75%;
  }

  .messages-area {
    padding: 10px 15px;
  }

  .message-bubble {
    padding: 8px 12px;
    font-size: 0.9rem;
  }

  .input-area {
    padding: 10px 15px;
  }

  .send-btn {
    height: 64px;
  }
}

/* 滚动条样式优化 */
.messages-area::-webkit-scrollbar {
  width: 4px;
}

.messages-area::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.messages-area::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.messages-area::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 确保在HomeView中正确显示 */
:deep(.Home-Main) {
  padding: 0 !important;
  height: 100%;
  overflow: hidden;
}
</style>
